package com.bdqn.wang.servlet;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.bdqn.wang.pojo.Comdity;
import com.bdqn.wang.pojo.ComdityAdd;
import com.bdqn.wang.pojo.ComdityAdm;
import com.bdqn.wang.pojo.User;
import com.bdqn.wang.service.ComdityAddService;
import com.bdqn.wang.service.ComdityAdmService;
import com.bdqn.wang.service.ComdityService;
import com.bdqn.wang.service.impl.ComdityAddServiceImpl;
import com.bdqn.wang.service.impl.ComdityAdmServiceImpl;
import com.bdqn.wang.service.impl.ComdityServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@WebServlet(urlPatterns = {"/product"})
public class ProductServlet extends HttpServlet {

    ComdityAdmService comdityAdmService = new ComdityAdmServiceImpl();
    ComdityAddService comdityAddService = new ComdityAddServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String opr = req.getParameter("opr");
        if("toadm".equals(opr)){
            List<ComdityAdm> comdityAdmList = comdityAdmService.getAll();
            req.getSession().setAttribute("toadm",comdityAdmList);
            req.getRequestDispatcher("/WEB-INF/product/commodityadm.jsp").forward(req,resp);
        }else if ("getcomdityAdmById".equals(opr)){
            String id = req.getParameter("id");
            ComdityAdm comdityAdm = comdityAdmService.getcomdityAdmById(Integer.parseInt(id));
            List<ComdityAdd> list1 = comdityAddService.getAll();
            req.getSession().setAttribute("list", list1);

            List<ComdityAdd> list2 =comdityAddService.getAll(comdityAdm.getCategoryLevel1Id());
            req.getSession().setAttribute("list2", list2);

            List<ComdityAdd> list3 =comdityAddService.getAll(comdityAdm.getCategoryLevel2Id());
            req.getSession().setAttribute("list3", list3);

            req.getSession().setAttribute("comdityAdm", comdityAdm);

            req.getRequestDispatcher("/WEB-INF/product/commodity_update.jsp").forward(req, resp);
        }else if ("admSava".equals(opr)){           //修改
            String realPath = req.getSession().getServletContext().getRealPath("static/img/");
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            //设置上传文件大小
            upload.setSizeMax(1024 * 1024);
            ComdityAdm comdityAdm = new ComdityAdm();
            try {
                //解析请求
                List list = upload.parseRequest(req);
                //通过迭代器 循环取出数据
                Iterator iterator = list.iterator();
                //判断时候还有元素
                while (iterator.hasNext()) {
                    //强转数据类型
                    FileItem item = (FileItem) iterator.next();
                    //判断是否是文件字段 ture代表是 false代表不是
                    if (item.isFormField()) {
                        String fieldname = item.getFieldName();
                        if (fieldname.equals("categoryLevel1Id")) {
                            String categoryLevel1Id = item.getString("UTF-8");
                            System.out.println(categoryLevel1Id);
                            comdityAdm.setCategoryLevel1Id(Integer.parseInt(categoryLevel1Id));
                        } else if (fieldname.equals("two")) {
                            String two = item.getString("UTF-8");
                            System.out.println(two);
                            comdityAdm.setCategoryLevel2Id(Integer.parseInt(two));
                        } else if(fieldname.equals("three")){
                            String three = item.getString("UTF-8");
                            System.out.println(three);
                            comdityAdm.setCategoryLevel3Id(Integer.parseInt(three));
                        } else if(fieldname.equals("name")){
                            String name = item.getString("UTF-8");
                            System.out.println(name);
                            comdityAdm.setName(name);
                        } else  if(fieldname.equals("price")){
                            String price = item.getString("UTF-8");
                            System.out.println(price);
                            comdityAdm.setPrice(Double.parseDouble(price));
                        } else if(fieldname.equals("stock")){
                            String stock = item.getString("UTF-8");
                            System.out.println(stock);
                            comdityAdm.setStock(Integer.parseInt(stock));
                        } else if(fieldname.equals("description")){
                            String description = item.getString("UTF-8");
                            System.out.println(description);
                            comdityAdm.setDescription(description);
                        }
                    } else {
                        //获取上传文件文件名
                        String filename = item.getName();
                        //定义合法后缀集合
                        List<String> types = new ArrayList<String>();
                        types.add("jpg");
                        types.add("jpeg");
                        types.add("png");
                        types.add("gif");
                        types.add("bmp");
                        types.add("ico");
                        //截取文件后缀
                        String houzhui = filename.substring(filename.lastIndexOf(".") + 1);
                        //判断是否包含此后缀
                        if (types.contains(houzhui)) {
                            //写入文件到服务器upload目录
                            String fileName = RandomUtil.randomUUID()+"."+houzhui;
                            comdityAdm.setFileName(fileName);
                            item.write(new File(realPath, fileName));

                        } else {
                            resp.getWriter().print("<h1>后缀不合法<h1>");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            int count = comdityAdmService.update(comdityAdm);
            if (count > 0) {
                resp.sendRedirect("Shopping?opr=toadm");
            }
        } else if("deladm".equals(opr)){
            String id = req.getParameter("id");
            int count = comdityAdmService.del(Integer.parseInt(id));
            if(count>0){
                req.getRequestDispatcher("product?opr=toadm").forward(req,resp);
            } else {
                resp.getWriter().print("<script>alert('删除失败')</script>");
            }


        }else if("toadd".equals(opr)){          //分类
            List<ComdityAdd> comdityAdds = comdityAddService.getAll();
            req.getSession().setAttribute("list",comdityAdds);
            req.getRequestDispatcher("/WEB-INF/product/commodityadd.jsp").forward(req,resp);
        }else if ("two".equals(opr)){           //二级分类
            int id=Integer.parseInt(req.getParameter("id"));
            List<ComdityAdd> list =comdityAddService.getAll(id);
            resp.getWriter().print(JSON.toJSONString(list));
        }else if ("three".equals(opr)){         //三级分类
            int id=Integer.parseInt(req.getParameter("ids"));
            List<ComdityAdd> list =comdityAddService.getAll(id);
            resp.getWriter().print(JSON.toJSONString(list));

        }else if("addSava".equals(opr)) {       //上架
            String realPath = req.getSession().getServletContext().getRealPath("static/img/");
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            //设置上传文件大小
            upload.setSizeMax(1024 * 1024);
            ComdityAdm comdityAdm = new ComdityAdm();
            try {
                //解析请求
                List list = upload.parseRequest(req);
                //通过迭代器 循环取出数据
                Iterator iterator = list.iterator();
                //判断时候还有元素
                while (iterator.hasNext()) {
                    //强转数据类型
                    FileItem item = (FileItem) iterator.next();
                    //判断是否是文件字段 ture代表是 false代表不是
                    if (item.isFormField()) {
                        String fieldname = item.getFieldName();
                        if (fieldname.equals("categoryLevel1Id")) {
                            String categoryLevel1Id = item.getString("UTF-8");
                            System.out.println(categoryLevel1Id);
                            comdityAdm.setCategoryLevel1Id(Integer.parseInt(categoryLevel1Id));
                        } else if (fieldname.equals("two")) {
                            String two = item.getString("UTF-8");
                            System.out.println(two);
                            comdityAdm.setCategoryLevel2Id(Integer.parseInt(two));
                        } else if(fieldname.equals("three")){
                            String three = item.getString("UTF-8");
                            System.out.println(three);
                            comdityAdm.setCategoryLevel3Id(Integer.parseInt(three));
                        } else if(fieldname.equals("name")){
                            String name = item.getString("UTF-8");
                            System.out.println(name);
                            comdityAdm.setName(name);
                        } else  if(fieldname.equals("price")){
                            String price = item.getString("UTF-8");
                            System.out.println(price);
                            comdityAdm.setPrice(Double.parseDouble(price));
                        } else if(fieldname.equals("stock")){
                            String stock = item.getString("UTF-8");
                            System.out.println(stock);
                            comdityAdm.setStock(Integer.parseInt(stock));
                        } else if(fieldname.equals("description")){
                            String description = item.getString("UTF-8");
                            System.out.println(description);
                            comdityAdm.setDescription(description);
                        }
                    } else {
                        //获取上传文件文件名
                        String filename = item.getName();
                        //定义合法后缀集合
                        List<String> types = new ArrayList<String>();
                        types.add("jpg");
                        types.add("jpeg");
                        types.add("png");
                        types.add("gif");
                        types.add("bmp");
                        types.add("ico");
                        //截取文件后缀
                        String suffix = filename.substring(filename.lastIndexOf(".") + 1);
                        //判断是否包含此后缀
                        if (types.contains(suffix)) {
                            //写入文件到服务器upload目录
                            String fileName = RandomUtil.randomUUID()+"."+suffix;
                            comdityAdm.setFileName(fileName);
                            item.write(new File(realPath, fileName));

                        } else {
                            resp.getWriter().print("<h1>后缀不合法<h1>");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            int count = comdityAdmService.add(comdityAdm);
            if (count > 0) {
//                req.setAttribute("msg", "新增商品信息成功！");
                req.getRequestDispatcher("product?opr=toadm").forward(req,resp);
            } else {

            }
        }

    }
}
